package cn.iocoder.yudao.module.pay.transfer.mq;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.module.api.pay.transfer.enums.UnifiedTransferStatusEnum;
import cn.iocoder.yudao.module.api.pay.transfer.message.TransferDealingMessage;
import cn.iocoder.yudao.module.api.pay.transfer.message.TransferFailureMessage;
import cn.iocoder.yudao.module.api.pay.transfer.message.TransferSuccessMessage;
import cn.iocoder.yudao.module.pay.cashout.service.AppPayCashOutRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 转账单据 事件消费者
 *
 * @author 山野羡民（1032694760@qq.com）
 */
@Component
@Slf4j
public class TransferConsumer {

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(TransferDealingMessage message) {
        log.info("[pay/transfer][onMessage][转账处理中事件({})]", message);
        if (message.getOutTransferNo().matches("\\d+")) {
            Long recordId = NumberUtil.parseLong(message.getOutTransferNo());
            SpringUtil.getBean(AppPayCashOutRecordService.class).updateTransferStatus(recordId, UnifiedTransferStatusEnum.DEALING.getValue());
        }
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(TransferSuccessMessage message) {
        log.info("[pay/transfer][onMessage][转账成功事件({})]", message);
        if (message.getOutTransferNo().matches("\\d+")) {
            Long recordId = NumberUtil.parseLong(message.getOutTransferNo());
            SpringUtil.getBean(AppPayCashOutRecordService.class).updateTransferStatus(recordId, UnifiedTransferStatusEnum.SUCCESS.getValue());
        }
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(TransferFailureMessage message) {
        log.info("[pay/transfer][onMessage][转账失败事件({})]", message);
        if (message.getOutTransferNo().matches("\\d+")) {
            Long recordId = NumberUtil.parseLong(message.getOutTransferNo());
            SpringUtil.getBean(AppPayCashOutRecordService.class).updateTransferStatus(recordId, UnifiedTransferStatusEnum.CLOSED.getValue());
        }
    }

}
